import { Component, OnInit } from "@angular/core";
import { NzNotificationService, UploadFile } from "ng-zorro-antd";
import { Router, ActivatedRoute } from "@angular/router";
import { HttpServcie} from "../../../service/http.service";
import { Config } from "../../../service/config";
import { NzModalService, NzModalSubject } from "ng-zorro-antd";
import { SpotObjectPlan} from "../bean/spotObjectPlan";
import * as moment from "moment";

@Component({
  selector: "spot-object-census",
  templateUrl: "spot-object-census.html",
  styleUrls: ["spot-object-census.scss"]
})
export class SpotObjectCensus implements OnInit {

  public isSpinning: boolean = false;

  // 定义实施对象实体类
  public objectPlan:SpotObjectPlan= new SpotObjectPlan();
  // 定义查询多少条数据
  public total = 0;
  // 定义数据
  public list: any = [];
  // 定义模态框表头
  public modelTitle: string;
  // 定义模态框类型
  public modal: number;
  // 定义当前登录人
  public user:any=[];
  // 定义计划集合
  public planList:any=[];
  // 定义查询的值
  public selectValue:any;
  // 定义时间端
  public startDate:any = null;
  public endDate:any = null;

  // 定义导出记录表
  public exportTable:any=[];
  // 定义详情数据
  public detailsData:any=[];



  newArray = len => {
    const result = [];
    for (let i = 0; i < len; i++) {
      result.push(i);
    }
    return result;
  };

  _startValueChange = () => {
    if (this.startDate > this.endDate) {
      this.endDate = null;
    }
  };
  _endValueChange = () => {
    if (this.startDate > this.endDate) {
      this.startDate = null;
    }
  };
  _disabledStartDate = startValue => {
    if (!startValue || !this.endDate) {
      return false;
    }
    return startValue.getTime() >= this.endDate.getTime();
  };
  _disabledEndDate = endValue => {
    if (!endValue || !this.startDate) {
      return false;
    }
    return endValue.getTime() <= this.startDate.getTime();
  };

  get _isSameDay() {
    return (
      this.startDate &&
      this.endDate &&
      moment(this.startDate).isSame(this.endDate, "day")
    );
  }
  get _endTime() {
    return {
      nzHideDisabledOptions: true,
      nzDisabledHours: () => {
        return this._isSameDay ? this.newArray(this.startDate.getHours()) : [];
      },
      nzDisabledMinutes: h => {
        if (this._isSameDay && h === this.startDate.getHours()) {
          return this.newArray(this.startDate.getMinutes());
        }
        return [];
      },
      nzDisabledSeconds: (h, m) => {
        if (
          this._isSameDay &&
          h === this.startDate.getHours() &&
          m === this.startDate.getMinutes()
        ) {
          return this.newArray(this.startDate.getSeconds());
        }
        return [];
      }
    };
  }


  updateData: any;
  allChecked = false;
  indeterminate = false;
  currentModal: any;
  isConfirmLoading = false;
  isAddVisible = false;
  config = Config;

  constructor(
    private httpServcie: HttpServcie,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService
  ) {

    this.objectPlan.currentPage = 1;
    this.objectPlan.pageSize = 10;

    //查询
    this.query();



  }

  ngOnInit() {
    this.user = JSON.parse(window.localStorage.getItem("user"));

  }
  // 查询方法
  query() {

    let currentPage =  this.objectPlan.currentPage;
    let pageSize  = this.objectPlan.pageSize;

    if(this.startDate !=null && this.startDate !=undefined){
      this.startDate = this.startDate ? moment(this.startDate).format("YYYYMMDDHHmmss") : "";
    }

    if(this.endDate !=null && this.endDate !=undefined){
      this.endDate = this.endDate ? moment(this.endDate).format("YYYYMMDDHHmmss") : "";
    }


    let plans:any=[];
    let partyId = JSON.parse(window.localStorage.getItem("user")).partyId;
    this.httpServcie.spotObjectCensus({"implementObject":this.selectValue,"startDate":this.startDate,"endDate":this.endDate,"currentPage":currentPage,"pageSize":pageSize,"partyId":partyId}).subscribe(data => {
      console.log(data)
      if (data.status == 200) {

        this.list = data.data.list;
        this.total = data.data.total;

        for (let i = 0; i < data.data.list.length; i++) {
          if (plans.indexOf(data.data.list[i].implementObject) == -1) {
            plans.push(data.data.list[i].implementObject);
          }
        }
        this.planList = plans;

      } else if (data.status == 401) {
        this._notification.create("error", "失败", "请重新登录");
        this.router.navigateByUrl("/login");
      } else if (data.status == 401) {
        this._notification.create("error", "失败", "请重新登录");
        this.router.navigateByUrl("/login");
      } else {
        this._notification.create("error", "失败", "查询出错！请重试");
      }
    });
  }

  // 查询面板
  panels = {
    active: true,
    name: "查询",
    disabled: false,
    childPanel: [
      {
        active: false,
        name: "查询"
      }
    ]
  };

  //table加载数据时
  displayDataChange($event) {
    this.list = $event;
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.list.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.list.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }

  //全选
  checkAll(value) {
    if (value) {
      this.list.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.list.forEach(data => (data.checked = false));
    }
  }

  //分页
  nzPageSizeChange(event) {
    this.objectPlan.pageSize = event;
    this.objectPlan.currentPage = 1;
    this.query();
  }

  //输入框的方法
  nzPageIndexChange(event) {
    this.objectPlan.currentPage = event;
    this.query();
  }

  //当前页
  nzPageIndexClickChange(event) {
    this.objectPlan.currentPage = event;
    this.query();
  }


  /**
   * 导出维保人员的检查项
   */
  exportExcelObj(data) {
    let planId = data.planId;
    let elevatorId = data.elevatorId;
    let implementObject = data.implementObject;
    let checkMan = data.checkMan;
    console.log(this.config.IP);
    let iplink = this.config.IP;
    // https替换
    iplink = iplink.replace('https', 'http');
    iplink = iplink.replace(iplink.substring(this.find(iplink, ':', 1) + 1, iplink.length - 1), '8099');
    console.log(iplink);
    window.open(iplink + "ureport/preview?_u=file:checkItemReport.ureport.xml&_t=1,2,4,5,6&planId=" + planId + "&elevatorId=" + elevatorId + "&implementObject=" + implementObject + "&checkMan=" + checkMan);
  }

  /**
   * 查找指定字符所在的位置
   * @param str
   * @param cha
   * @param num
   */
  find(str, cha, num) {
    let x = str.indexOf(cha);
    for(let i = 0; i < num; i++) {
      x = str.indexOf(cha, x + 1);
    }
    return x;
  }

  /**
   * 计划汇总导出
   * @param url
   * @param name
   */
  planExcel(){

    let planList:any=[];
    this.list.forEach(element => {
      if (element.checked) {
        planList.push(element.planId);
        this.exportTable.push(element);
      }
    });
    if(planList.length==0 || planList == null){
      this._notification.create("warning", "警告提示", "请先勾选您要导出的数据！");
      return  false;
    }
    if(planList.length >1 ){
      for(var i=0;i<this.planList.length-1;i++){
        if(planList[i] !=planList[i+1]){
          this._notification.create("warning", "警告提示", "请选择同一个计划名称");
          return false;
        }
      }
    }
    this.isSpinning=true;

    this.httpServcie.exportExcelObj({table:this.exportTable}).subscribe(data => {
      if (data.status == 200) {
        this.download(data.data.fileUrl, data.data.fileName);
        this.isSpinning=false;
        this._notification.create("success", "提示", "导出成功");
      } else {
        this._notification.create("error", "提示", data.error);
      }
    });
  }




  download(url, name) {
    let link = document.createElement("a");
    let body = document.querySelector("body");

    this.getBlob(this.config.IP + this.config.API.getUpload + url).then(
      blob => {
        link.href = window.URL.createObjectURL(blob);
        link.download = name;
        // fix Firefox
        link.style.display = "none";
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      }
    );
  }
  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }


  //关闭model框
  handleCancel = e => {
    console.log(e);
    this.isAddVisible = false;
  };

  // 添加界面打开
  details(titleTpl, contentTpl, footerTpl,data) {
    this.detailsData = data;

    this.modelTitle = "详情";
    this.modal = 0;
    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 900,
      zIndex: 100,
      style: {
        top: "40px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }


}
